﻿using SaaS.Cache.Systems;
using SaaS.Model.Entity.Systems;
using SaaS.Model.Enums;
using SaaS.Model.Enums.Systems;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Web.System.Services.Systems
{
    public class SettingAppService : SystemApplicationServiceBase
    {
        private readonly SettingCacheService _settingCacheService;
        public SettingAppService(SettingCacheService settingCacheService)
        {
            _settingCacheService = settingCacheService;
        }
        /// <summary>
        /// 获取所有配置
        /// </summary>
        /// <returns></returns>
        public IDictionary<SettingType, string> GetSettings()
        {
            return SDC.SystemSettings.ToDictionary(c => c.Id, c => c.Value);
        }
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SaveSetting(SettingType type, string value)
        {
            if (SDC.SystemSettings.Any(c => c.Id == type))
            {
                Repository.Update<SystemSetting, SettingType, string>(c => c.Id == type, c => c.Value, value);
            }
            else
            {
                Repository.Insert<SystemSetting, SettingType>(new SystemSetting { Id = type, Value = value });
            }
            _settingCacheService.SaveSetting(type, value);
            return Logger.Log("保存配置", SystemLoggerSource.Setting);
        }
    }
}
